//
//  LKEmotionToolBar.swift
//  新浪微博
//
//  Created by 胡不归是大虾 on 2016/10/9.
//  Copyright © 2016年 胡不归是大虾. All rights reserved.
//
enum EmotionType: Int {
    case RECENT = 0
    case DEFAULT
    case EMOJI
    case LXH
}
import UIKit


class LKEmotionToolBar: UIStackView {
    ///记录上一次点击的按钮
    var lastBtn : UIButton?
    ///传递按钮点击事件的闭包
    var emotionBtnClickClosure: ((EmotionType)->())?
    override init(frame: CGRect) {
        super.init(frame: frame)
        //设置轴
        axis = .horizontal
        //设置填充方式
        distribution = .fillEqually
        //父视图默认占用tag=0
        self.tag = 10000
        setMyUI()
    }
    
    required init(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    //更新UI
    private func setMyUI () {
        addChildBtns(title: "最近", bgImage: "compose_emotion_table_left", index: .RECENT)
        addChildBtns(title: "默认", bgImage: "compose_emotion_table_mid", index: .DEFAULT)
        addChildBtns(title: "Emoji", bgImage: "compose_emotion_table_mid", index: .EMOJI)
        addChildBtns(title: "浪小花", bgImage: "compose_emotion_table_right", index: .LXH)
    }
    //添加按钮
    private func addChildBtns (title:String , bgImage: String, index:EmotionType) {
        let btn = UIButton()
        //按钮的索引,作为唯一标记
        btn.tag = index.rawValue
        btn.setBackgroundImage(UIImage(named: bgImage + "_normal"), for: .normal)
        btn.setBackgroundImage(UIImage(named: bgImage + "_selected"), for: .selected)
        btn.setTitle(title, for: .normal)
        btn.setTitleColor(UIColor.white, for: .normal)
        btn.setTitleColor(UIColor.darkGray, for: .selected)
        //添加按钮点击事件
        btn.addTarget(self, action: #selector(bottomToolBarBtnDidClick(btn:)), for: .touchUpInside)
        self.addArrangedSubview(btn)
        if index == .RECENT
        {
            //设置默认第一个被选中
            btn.isSelected = true
            //记录上次被选中的按钮
            lastBtn = btn
        }
    }
    //按钮点击方法实现
    @objc private func bottomToolBarBtnDidClick (btn:UIButton){
        if btn.isSelected {
            //按钮已经是选中状态,拦截
            return
        }
        //否则的话先取消上次按钮的选中状态
        lastBtn?.isSelected = false
        //记录选中的按钮
        lastBtn = btn
        //点击的按钮改为选中状态
        btn.isSelected = true
        //用闭包传递按钮的点击事件
        emotionBtnClickClosure?(EmotionType.init(rawValue: btn.tag)!)
    }
    func setEmotionToolBarBtnSelected(indexPath: IndexPath){
        //获取按钮
        let btn = self.viewWithTag(indexPath.section) as! UIButton
        //如果已经是选中状态则拦截
        if btn.isSelected {
            return
        }
        lastBtn?.isSelected = false
        lastBtn = btn
        btn.isSelected = true
    }
}
